package Server.Socket;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;


import JFrame.BuySell;

public class Client extends JFrame implements Runnable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//客户端程序
	//创建Socket通信端口号常量
	public static final int PORT = 8765;
	
	Socket socket;
	Thread thread;
	
	//声明客户端数据输入输出流
	DataInputStream in;
	DataOutputStream out;
	
	//声明字符串：用户名，从服务器收到的消息，客户发言信息
	String name,chat_in,chat_txt;
	InetAddress addr = null;
	
	public Client(){
		
		try {
			addr = InetAddress.getByName("localhost");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}    
	}
	
	
	public void buy(String chatStr){
		chat_txt =chatStr;
		try
		{
			socket = new Socket(addr,PORT);
			in = new DataInputStream(socket.getInputStream());
			out = new DataOutputStream(socket.getOutputStream());
			out.writeUTF("<buy>"+chat_txt);
			System.out.println("sell发送给服务器端信息："+chat_txt);
		}catch(IOException e1){
			e1.printStackTrace();
		}
		thread = new Thread(this);
		thread.start();
		
	}
    
	public void sell(String chatStr){
		chat_txt = chatStr;  
		try
		{
			socket = new Socket(addr,PORT);
			in = new DataInputStream(socket.getInputStream());
			out = new DataOutputStream(socket.getOutputStream());
			out.writeUTF("<sell>"+chat_txt);
			System.out.println("sell发送给服务器端信息："+chat_txt);
		}catch(IOException e1){
			e1.printStackTrace();
		}
		thread = new Thread(this);
		thread.start();
		
	}
	
	@Override
	public void run() {
		
		while(true)
		{
			try
			{
				//读取服务器发来的信息
				chat_in = in.readUTF();
				System.out.println("服务器发来的信息:"+chat_in);
				String s =chat_in.substring(0,6);
				if(s.equals("Server")){
					BuySell.jTextField5.setText(chat_in.substring(6));
					out.writeUTF("ByeBye"+name);
					break;
				}
				
			}catch(IOException e){
				e.printStackTrace();
			}
				
		}
		
		try {
			out.close();
			in.close();
			socket.close();
			this.setVisible(false);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	
}
